package com.earl.gsm.service.impl.place;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.earl.gsm.commons.dao.BaseDao;
import com.earl.gsm.commons.service.BaseServiceImpl;
import com.earl.gsm.dao.PlaceDao;
import com.earl.gsm.dao.PlaceOrderDao;
import com.earl.gsm.domain.gsm.place.Place;
import com.earl.gsm.domain.gsm.place.PlaceOrder;
import com.earl.gsm.exception.ApplicationException;
import com.earl.gsm.service.PlaceOrderService;

@Service
@Transactional
public class PlaceOrderServiceImpl extends BaseServiceImpl<PlaceOrder, PlaceOrder>
        implements PlaceOrderService {

    private static Logger logger = Logger.getLogger(PlaceOrderServiceImpl.class);

    @Resource
    private PlaceOrderDao dao;
    
    @Resource
    private PlaceDao placeDao;

    @Override
    protected BaseDao<PlaceOrder> getDao() {
        return dao;
    }

    @Override
    public void saveOrder(PlaceOrder placeOrder){
    	
    	Date begin = null;
    	Date end = null ;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			begin = sdf.parse(placeOrder.getBeginTime());
			end =  sdf.parse(placeOrder.getEndTime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	
    	if(!dao.isSatisfyPlace(begin.getTime(),end.getTime())){
    		throw new ApplicationException("选择时间端无效");
    	}
    	
    	Place place = placeDao.findOneById(placeOrder.getPlaceId());
    	
    	placeOrder.setOutOfDate(false);
    	placeOrder.setBeginMillis(begin.getTime());
    	placeOrder.setEndMillis(end.getTime());
    	placeOrder.setPrice(place.getPrice());
    	placeOrder.setTotal((end.getTime() - begin.getTime()) * place.getPrice());
    	placeOrder.setUserId(1L);//TODO
    	dao.insert(placeOrder);
    }

	@Override
	public void updateOutOfDate() {
		// TODO Auto-generated method stub
		dao.updateOutOfDate();
	}
    
    
}
